<?php
namespace app\common\library;
/**
 * 加解密
 *
 */
class ModSecurity
{

    public static $key_t = 'mtetbpryjhdxmnhx';//设置加密

    public static function encrypt($input) {
        $key=self::$key_t;

		$data = openssl_encrypt($input, 'AES-128-ECB', $key,OPENSSL_RAW_DATA);

        $data = base64_encode($data);
        $data=  str_replace("+","_", $data);
        return $data;
    } 
    private static function pkcs5_pad ($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
     public static function decrypt($dStr,$type=0) {
        $dStr = urldecode($dStr);
        $dStr=  str_replace("_","+",$dStr);
        $dStr = base64_decode($dStr);
        $dKey=self::$key_t;
		$decrypted = openssl_decrypt($dStr, 'AES-128-ECB',$dKey,OPENSSL_RAW_DATA);
    
        if(strpos($decrypted,'_passwd_') !==false){
            if($type==1){
                $decrypted = explode('_passwd_',$decrypted);
                $decrypted = $decrypted;
                $arr = array(
                    'uid'=>$decrypted[0],
                    'passwd'=>$decrypted[1]
                );

                $decrypted = $arr;
            }else{
                $decrypted = explode('_passwd_',$decrypted);
                $decrypted = $decrypted[0];
            }
        }elseif(strpos($decrypted,'passwd') !==false && strpos($decrypted,'user_id') !==false){
            //解决m站单点登录问题
            $obj = json_decode($decrypted, true);
            if (is_array($obj)) {

                if($type==1) {
                    $arr = array(
                        'uid' => $obj['user_id'],
                        'passwd' => $obj['passwd']
                    );
                    $decrypted = $arr;
                }else {
                    $decrypted = $obj['user_id'];
                }
            }
        }

        return $decrypted;
    }
}
